import { View, Text, Image,ScrollView,Button } from "@tarojs/components";
import Taro, { useLoad, useShareAppMessage,useDidShow } from "@tarojs/taro";
import "./index.scss";
import { useState } from "react";
import { request } from "@/utils/request";
import { markPhone,getRoleValue } from "@/utils/tools";
import { AtFloatLayout, AtGrid, AtIcon } from "taro-ui";
// 图片
const dadImg =
  "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/dad.png";
const momImg =
  "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/mom.png";

const sonImg =
  "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/son.png";
const daughterImg =
  "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/daughter.png";
const husbandImg =
  "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/husband.png";
const wifeImg =
  "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/wife.png";

let selectFamilyRelationsValue1 : number;
let selectFamilyRelationsValue2 : number;
let selectFamilyRelationsItem2 : any = null;
const familySelectorList = [
  {
    image: dadImg,
    value: "爸爸",
  },
  {
    image: momImg,
    value: "妈妈",
  },
  {
    image: sonImg,
    value: "儿子",
  },
  {
    image: daughterImg,
    value: "女儿",
  },
  {
    image: husbandImg,
    value: "丈夫",
  },
  {
    image: wifeImg,
    value: "妻子",
  },
];
export default function MyFamilyGroup() {
  const [havingFamilyGroup, setHavingFamilyGroup] = useState(false);
  const [familyGroupList, setFamilyGroupList] = useState<any[]>([]);
  const custPhone = markPhone(Taro.getStorageSync("custPhone"));
  const [showAddFamily, setShowAddFamily] = useState(false);
  const [familyRelationsShow2Title, setFamilyRelationsShow2Title] = useState('');
  const [familyRelationsArr2, setFamilyRelationsArr2] = useState<any[]>([]);
  const [familyRelationsShow2, setFamilyRelationsShow2] = useState(false);

  
  function getFamilyGroupList() {
    request({
      url: "/api/points/family/queryList",
      data: {
        token: Taro.getStorageSync("token"),
        openId: Taro.getStorageSync("openid"),
      },
      success(data) {
        let respDataList = data.respDataList;
        // console.log("MyFamilyGroup respDataList:", respDataList);
        if (respDataList && respDataList.length > 0) {
          let familyGroupList: any[] = [];
          for (let i = 0; i < respDataList.length; i++) {
            let item = respDataList[i];
            let obj = {
              id: item.id,
              groupId: item.groupId,
              nick: item.nick,
              imgSrc: "",
              custPhone: item.custPhone,
              toUserDesc: "",
              imgSrc1: "",
              inviteUserDesc: "",
              imgSrc2: "",
              inviteStatus: item.inviteStatus,
              delBtnShow: false,
              showRoleName: "",
              showRolePhone: "",
              hasHealthRecords: item.hasHealthRecords,
              patientId: item.patientId,
            };
            // inviteUserDesc 发起邀请的人
            if (item.inviteUserDesc == "1") {
              obj.inviteUserDesc = "爸爸";
              obj.imgSrc2 = dadImg;
            } else if (item.inviteUserDesc == "2") {
              obj.inviteUserDesc = "妈妈";
              obj.imgSrc2 = momImg;
            } else if (item.inviteUserDesc == "3") {
              obj.inviteUserDesc = "儿子";
              obj.imgSrc2 = sonImg;
            } else if (item.inviteUserDesc == "4") {
              obj.inviteUserDesc = "女儿";
              obj.imgSrc2 = daughterImg;
            } else if (item.inviteUserDesc == "5") {
              obj.inviteUserDesc = "丈夫";
              obj.imgSrc2 = husbandImg;
            } else if (item.inviteUserDesc == "6") {
              obj.inviteUserDesc = "妻子";
              obj.imgSrc2 = wifeImg;
            }
            // 被邀请的人
            if (item.toUserDesc == "1") {
              obj.toUserDesc = "爸爸";
              obj.imgSrc1 = dadImg;
            } else if (item.toUserDesc == "2") {
              obj.toUserDesc = "妈妈";
              obj.imgSrc1 = momImg;
            } else if (item.toUserDesc == "3") {
              obj.toUserDesc = "儿子";
              obj.imgSrc1 = sonImg;
            } else if (item.toUserDesc == "4") {
              obj.toUserDesc = "女儿";
              obj.imgSrc1 = daughterImg;
            } else if (item.toUserDesc == "5") {
              obj.toUserDesc = "丈夫";
              obj.imgSrc1 = husbandImg;
            } else if (item.toUserDesc == "6") {
              obj.toUserDesc = "妻子";
              obj.imgSrc1 = wifeImg;
            }
            
            // if (item.inviteStatus == "0") {
            //   obj.inviteStatus = "等待确认";
            //   obj.delBtnShow = false;
            // } else if (item.inviteStatus == "1") {
            //   obj.inviteStatus = "已开通";
            //   if (item.inviteUserId == Taro.getStorageSync("user").id) {
            //     obj.delBtnShow = true;
            //   } else {
            //     obj.delBtnShow = false;
            //   }
            // } else if (item.inviteStatus == "2") {
            //   obj.inviteStatus = "已拒绝";
            //   if (item.inviteUserId == Taro.getStorageSync("user").id) {
            //     obj.delBtnShow = true;
            //   } else {
            //     obj.delBtnShow = false;
            //   }
            // }
            // 被邀请人的openid不为空
            if (item.toUserOpenid != "") {
              // 被邀请人打开
              console.log('toUserOpenid')
              if (item.toUserOpenid == Taro.getStorageSync("openid")) {
                console.log('toUserOpenid if')
                obj.showRoleName = obj.inviteUserDesc;
                // obj.showRolePhone = item.custPhone
                obj.imgSrc = obj.imgSrc2;
              } else {
                console.log('toUserOpenid else')
                // 发起邀请的人打开 家人列表
                if (item.inviteUserId == Taro.getStorageSync("user").id) {
                  obj.showRoleName = obj.toUserDesc;
                  obj.showRolePhone = item.custPhone;
                  obj.imgSrc = obj.imgSrc1;
                } else {
                  obj.showRoleName = "家人";
                  // obj.showRolePhone = item.custPhone
                  obj.imgSrc =
                    "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/whjk-minProgram/images/default-family-avatar.png";
                }
              }
            } else {
              // 发起邀请的人打开 家人列表
              if (item.inviteUserId == Taro.getStorageSync("user").id) {
                obj.showRoleName = obj.toUserDesc;
                // obj.showRolePhone = item.custPhone
                obj.imgSrc = obj.imgSrc1;
              } else {
                obj.showRoleName = "家人";
                // obj.showRolePhone = ''
                obj.imgSrc =
                  "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/whjk-minProgram/images/default-family-avatar.png";
              }
            }
            obj.custPhone = obj.custPhone
              ? obj.custPhone.slice(0, 3) + "****" + obj.custPhone.slice(7, 11)
              : "";

            familyGroupList.push(obj);
          }
          familyGroupList = familyGroupList.filter((item) => {
            return item.inviteStatus === 1;
          });
          setHavingFamilyGroup(true);
          setFamilyGroupList(familyGroupList);
        } else {
          setHavingFamilyGroup(false);
          setFamilyGroupList([]);
        }
      },
    });
  }
  
  useLoad(options => {
   console.log('useLoad options:',options) 
   if(options.showAddFamily ==='1'){
    setShowAddFamily(true)
   }
  })
  useDidShow(() => {
    console.log("Page loaded.");
    // 获取家庭列表
    getFamilyGroupList()
  });
  
  function familySelectorClick(selectItem) {
    console.log('familySelectorClick');
    setShowAddFamily(false)
    let value = selectItem.value
    selectFamilyRelationsValue1 = getRoleValue(value)

    setFamilyRelationsShow2Title('你是你' + value + '的？')
	
		let familyRelationsArr2 : {value:string, image:string}[] = []
		if (selectFamilyRelationsValue1 == 1 || selectFamilyRelationsValue1 == 2) {
			familyRelationsArr2 = [
				{
					value: '儿子',
					image: sonImg
				},
				{
					value: '女儿',
					image: daughterImg
				}
			]
		} else if (selectFamilyRelationsValue1 == 3 || selectFamilyRelationsValue1 == 4) {
			familyRelationsArr2 = [
				{
					value: '爸爸',
					image: dadImg
				},
				{
					value: '妈妈',
					image: momImg
				}
			]
		} else if (selectFamilyRelationsValue1 == 5) {
			familyRelationsArr2 = [
				{
					value: '妻子',
					image: wifeImg
				}
			]
		} else if (selectFamilyRelationsValue1 == 6) {
			familyRelationsArr2 = [
				{
					value: '丈夫',
					image: husbandImg
				}
			]
		}
		if (selectFamilyRelationsValue1 == 5 || selectFamilyRelationsValue1 == 6) {
      setFamilyRelationsShow2(false)
      console.log('familyRelationsArr2:',familyRelationsArr2)
      selectFamilyRelationsItem2 = familyRelationsArr2[0],
      selectFamilyRelationsValue2 = getRoleValue(familyRelationsArr2[0].value)
      console.log('selectFamilyRelationsItem2:',selectFamilyRelationsItem2)
		} else {
			setFamilyRelationsShow2(true)
		}
		
    setFamilyRelationsArr2(familyRelationsArr2)
  }

  function familySelectorClick2(selectItem) {
    console.log('familySelectorClick2 selectItem:',selectItem)
    selectFamilyRelationsValue2 = getRoleValue(selectItem.value)
    selectFamilyRelationsItem2 = selectItem
    setFamilyRelationsShow2(false)
    console.log('familySelectorClick2 selectFamilyRelationsItem2:',selectFamilyRelationsItem2)

  }
  useShareAppMessage((event:any)=>{
    console.log('useShareAppMessage event:',event)
    const promise = new Promise(resolve => {
      setTimeout(()=>{
        console.log('setTimeout')
        request({
          url: '/api/points/family/createActivity',
          data: {
            token: Taro.getStorageSync('token'),
            openId: Taro.getStorageSync('openid'),
            inviteUserDesc: Number(selectFamilyRelationsValue2),
            toUserDesc: Number(selectFamilyRelationsValue1)
          },
          method: 'post',
          success: function (respData) {
            console.log('useShareAppMessage selectFamilyRelationsItem2:',selectFamilyRelationsItem2)
            if(!selectFamilyRelationsItem2){

            }
            resolve({
              title: selectFamilyRelationsItem2.value + '邀请你加入家庭群',
              imageUrl: "https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/whjk-minProgram/images/family-share.png",
              path:  '/pages/index/index?groupId=' + respData.id + '&userPhone=' +
                Taro.getStorageSync('custPhone') +
                '&ruleDesc2='+selectFamilyRelationsItem2.value
            })
          }
        })
      },800)
    })
    return {
      title: '家庭群管理',
      path: '/pages/index/index',
      imageUrl: 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/image/share.png',
      promise
    }
  })
  return (
    <View className="content">
      <View className="myFamilyGroup">
        <View className="family-item">
          <View className="avatar">
            <View className="txt">我</View>
          </View>
          <View className="info">
            <View className="role">本人</View>
            <View className="phone">{custPhone}</View>
          </View>
        </View>
        {familyGroupList.map((familyMember, index) => {
          return (
            <View className="family-item" key={index}>
              <View className="avatar">
                <Image className="image" src={familyMember.imgSrc}></Image>
              </View>
              <View className="info">
                <View className="role">{familyMember.showRoleName}</View>
                <View className="phone">{familyMember.custPhone}</View>
              </View>
            </View>
          );
        })}
        <View className="bar"></View>
        <View
          className="family-item"
          onClick={() => {
            setShowAddFamily(true);
          }}
        >
          <View className="avatar">
            <View className="txt add">+</View>
          </View>
          <View className="info">
            <View className="role">添加成员</View>
          </View>
        </View>
      </View>
      <View
        className={["family-list-float", showAddFamily ? "show" : "hide"].join(
          " "
        )}
      >
        <View className="shadow"></View>

        <ScrollView className="family-content" scrollY>
          <View className="title">
            <Text className="txt">请选择要添加的亲人</Text>
            <AtIcon
              className="at-close"
              value="close"
              size="10"
              color="#999"
              onClick={() => {
                setShowAddFamily(false);
              }}
            ></AtIcon>
          </View>
          <View className='grid'>
            {
              familySelectorList.map((item,index)=>{
                return (
                  <View className='grid-item' key={index} >
                    <View className='grid-item-content' onClick={()=>{
                    familySelectorClick(item)
                  }}>
                      <Button className="btn" openType={(item.value==='丈夫'||item.value==='妻子') ? 'share':undefined}>
                        <View className='grid-item-img'>
                          <Image src={item.image} className='grid-item-img-image'></Image>
                        </View>
                        <View className='grid-item-name'>{item.value}</View>
                      </Button>
                      
                    </View>
                  </View>
                )
              })
            }
          </View>
          <View className="bar"></View>
          <View className="cancel-btn" onClick={() => {
                setShowAddFamily(false);
              }}>取消</View>
        </ScrollView>
        
      </View>
      {/* 第2次选择关系 */}
      <View
        className={["family-list-float", familyRelationsShow2 ? "show" : "hide"].join(
          " "
        )}
      >
        <View className="shadow"></View>

        <ScrollView className="family-content" scrollY>
          <View className="title">
            <Text className="txt">{familyRelationsShow2Title}</Text>
            <AtIcon
              className="at-close"
              value="close"
              size="10"
              color="#999"
              onClick={() => {
                setFamilyRelationsShow2(false);
              }}
            ></AtIcon>
          </View>
          <View className='grid'>
            {
              familyRelationsArr2.map((item,index)=>{
                return (
                  <View className='grid-item' key={index} onClick={()=>{
                    familySelectorClick2(item)
                  }}>
                    <Button className="btn" openType='share'>
                      <View className='grid-item-content'>
                        <View className='grid-item-img'>
                          <Image src={item.image} className='grid-item-img-image'></Image>
                        </View>
                        <View className='grid-item-name'>{item.value}</View>
                      </View>
                    </Button>
                    
                  </View>
                )
              })
            }
          </View>
          <View className="bar"></View>
          <View className="cancel-btn" onClick={() => {
                setFamilyRelationsShow2(false);
              }}>取消</View>
        </ScrollView>
        
      </View>
    </View>
  );
}
